package com.agil.calculadora.cotacao;

import java.io.*;
import java.net.URL;
import java.util.Scanner;

public class Cotacao {

    private Double cotacao;

    public void executar() {
        String strUrl = "http://quote.yahoo.com/d/quote.txt?s=usdbrl=X&f=l1&e=.txt";
        File file = new File("~/quote.txt");
        try {
            download(strUrl, file);
            URL url = new URL(strUrl);
            Scanner s = new Scanner(url.openStream());
            cotacao = Double.parseDouble(s.nextLine());
            System.out.println(cotacao.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }        
    }

    private void download(String link, File localFile) throws Exception {
        System.out.println("Downloading " + link);
        URL url = new URL(link);

        InputStream is = url.openStream();
        FileOutputStream fos = new FileOutputStream(localFile);

        copyStream(new BufferedInputStream(is), fos);

        fos.flush();
        fos.close();

        is.close();
    }

    private void copyStream(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int ix = 0;
        while ((ix = in.read(buffer)) > 0) {
            out.write(buffer, 0, ix);
        }
    }

    public Double getCotacao() {
        return cotacao;
    }

    public void setCotacao(Double cotacao) {
        this.cotacao = cotacao;
    }
}
